package tcp

import (
	"bytes"
	"encoding/binary"
	"lnzw/engine/log"
	"net"

	"go.uber.org/zap"
	"google.golang.org/protobuf/proto"
)

type ServerClient struct {
	*TcpSocket
	client *SocketClient
	addr   string
}

func NewServerClient() *ServerClient {
	return &ServerClient{TcpSocket: &TcpSocket{}}
}

func (c *ServerClient) BindAddress(address string) *ServerClient {
	c.addr = address
	return c
}

func (c *ServerClient) BindSocketHandle(socketHandle SocketHandle) *ServerClient {
	c.socketHandle = socketHandle
	return c
}

func (c *ServerClient) SendMsg(code int32, data []byte) {
	var buf bytes.Buffer
	bs := make([]byte, 4)
	binary.BigEndian.PutUint32(bs, uint32(code))
	buf.Write(bs)
	buf.Write(data)
	c.client.SendMsg(buf.Bytes())
}

func (c *ServerClient) SendPb(code int32, msg proto.Message) {
	bs, err := proto.Marshal(msg)
	c.SendMsg(code, bs)
	if err != nil {
		log.Logger.Error("SendPb error, marshal error", zap.Any("err", err))
	}
}

func (c *ServerClient) Start() {
	//tcp连接服务器
	conn, err := net.Dial("tcp", c.addr)
	if err != nil {
		log.Logger.Error("dial failed", zap.Error(err))
		return
	}
	client := buildClient(conn, c)
	c.client = client
	c.socketHandle.OnConnect(client)
	client.StartWork()
}
